package org.feng;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.Data;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author 01434188
 */
@Controller
@RequestMapping("/excelTemplate")
public class ExcelTemplateDemoController {

    @GetMapping("/erpFee")
    public String erpFee(HttpServletResponse response) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream template;
        try {
            template = new ClassPathResource("erp_fee_template.xlsx").getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        List<ErpFeeExcelData> exportList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ErpFeeExcelData data = new ErpFeeExcelData();
            data.setLineProject("data"+(i+1)+"行项目");
            data.setFactory("data"+(i+1)+"工厂");
            data.setFeeDesc("data"+(i+1)+"费用描述");
            data.setCompanyCode("data"+(i+1)+"公司编码");
            exportList.add(data);
        }

        ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(template).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(exportList, writeSheet);
        Map<String, String> totalMap = new HashMap<>();
        totalMap.put("lineProjectTitle", "我是行项目");
        excelWriter.fill(totalMap, writeSheet);
        excelWriter.finish();


        // 转码
        String filename = URLEncoder.encode("fee费用" + System.currentTimeMillis() + ".xlsx", "utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
        return "";
    }

    @Data
    public static class ErpFeeExcelData {
        private String lineProject;
        private String companyCode;
        private String feeDesc;
        private String factory;
    }
}
